package com.xiaomi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaomi.domain.UserEntity;
import com.xiaomi.mappers.UserMapper;
import com.xiaomi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<UserEntity> findPageUsers(Integer pageNum) {
        //设置分页信息
        PageHelper.startPage(pageNum, 5);
        //查询所有记录
        List<UserEntity> accounts = userMapper.findPageUsers();
        //封装到PageInfo中自动完成分页
        return new PageInfo<>(accounts);
    }

    @Override
    public boolean deleteUsersById(String[] ids) {
        return userMapper.deleteUsersById(ids) == ids.length ? true : false;
    }

    @Override
    public boolean updateManager(String uid, Integer manager) {
        return userMapper.updateManager(uid, manager) == 1 ? true : false;
    }

    @Override
    public UserEntity getUserByPhone(String phone) {
        return userMapper.getUserByPhone(phone);
    }

    @Override
    public boolean isRegister(String phone, String userName) {
        return userMapper.isRegister(phone, userName) == 1 ? true : false;
    }

    @Override
    public boolean register(UserEntity user, String realPath, MultipartFile photo_) {
        if (photo_.getSize() != 0) {
            File storeDirectory = new File(realPath);
            if (!storeDirectory.exists())
                storeDirectory.mkdirs();

            //文件改名：UUID文件名（唯一）
            String originalFilename = photo_.getOriginalFilename();//原文件名：比如a.jpg
            String filename = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            //上传
            try {
                photo_.transferTo(new File(storeDirectory, filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
            user.setPhoto(filename);
        }

        user.setManager(1);
        user.setCreateTime(new Date());
        return userMapper.register(user) == 1 ? true : false;
    }

    // 管理员登录
    @Override
    public UserEntity getUserByUsernamePwd(String username, String password) {
        UserEntity admin = userMapper.getUserByUsernamePwd(username,password);

        return admin;
    }

}
